﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Mohe.Scada.Util.Exceptions;
using Mohe.Scada.Util.Models;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;

namespace Mohe.Scada.WebApi.Common.Filters
{
    public class GlobalExceptionsFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            var exception = context.Exception;

            var httpContext = context.HttpContext;
            var httpRequest = httpContext.Request;
            var type = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
            ApiResult result = new ApiResult();
            if (exception is CustomException myApiex)
            {
                context.HttpContext.Response.StatusCode = 200;
                context.ExceptionHandled = true;
                result.Message = "系统异常";
                result.Code = 500;
            }
            else
            {
                result.Message = "系统异常";
                result.Code = 500;
            }
            JsonSerializerOptions options = new JsonSerializerOptions()
            {
                WriteIndented = true,                                   //格式化json字符串
                AllowTrailingCommas = true,                             //可以结尾有逗号
                                                                        //IgnoreNullValues = true,                              //可以有空值,转换json去除空值属性
                IgnoreReadOnlyProperties = true,                        //忽略只读属性
                PropertyNameCaseInsensitive = true,                     //忽略大小写
                                                                        //PropertyNamingPolicy = JsonNamingPolicy.CamelCase     //命名方式是默认还是CamelCase
                Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
            };
            context.Result = new JsonResult(result, options);

        }
    }
}
